import { View, ScrollView } from '@tarojs/components'
import { useState, useEffect, useRef, useCallback, useMemo } from 'react'
import './VirtualList.scss'

const VirtualList = ({
  data = [],
  itemHeight = 200,
  containerHeight = 600,
  overscan = 5, // 预渲染的额外项目数
  renderItem,
  className = '',
  onScroll,
  ...props
}) => {
  const [scrollTop, setScrollTop] = useState(0)
  const scrollViewRef = useRef(null)
  const containerRef = useRef(null)

  // 计算可见区域的项目
  const visibleRange = useMemo(() => {
    const startIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - overscan)
    const endIndex = Math.min(
      data.length - 1,
      Math.ceil((scrollTop + containerHeight) / itemHeight) + overscan
    )
    
    return { startIndex, endIndex }
  }, [scrollTop, containerHeight, itemHeight, data.length, overscan])

  // 计算总高度和偏移量
  const totalHeight = data.length * itemHeight
  const offsetY = visibleRange.startIndex * itemHeight

  // 获取可见项目
  const visibleItems = useMemo(() => {
    return data.slice(visibleRange.startIndex, visibleRange.endIndex + 1)
  }, [data, visibleRange.startIndex, visibleRange.endIndex])

  // 处理滚动事件
  const handleScroll = useCallback((e) => {
    const { scrollTop: newScrollTop } = e.detail
    setScrollTop(newScrollTop)
    onScroll?.(e)
  }, [onScroll])

  // 滚动到指定索引
  const scrollToIndex = useCallback((index) => {
    if (scrollViewRef.current) {
      const targetScrollTop = index * itemHeight
      scrollViewRef.current.scrollTo({
        top: targetScrollTop,
        behavior: 'smooth'
      })
    }
  }, [itemHeight])

  // 滚动到顶部
  const scrollToTop = useCallback(() => {
    scrollToIndex(0)
  }, [scrollToIndex])

  // 滚动到底部
  const scrollToBottom = useCallback(() => {
    scrollToIndex(data.length - 1)
  }, [scrollToIndex, data.length])

  return (
    <View className={`virtual-list ${className}`} ref={containerRef}>
      <ScrollView
        ref={scrollViewRef}
        className='virtual-scroll-view'
        scrollY
        style={{ height: containerHeight }}
        onScroll={handleScroll}
        {...props}
      >
        {/* 占位符，设置总高度 */}
        <View 
          className='virtual-placeholder'
          style={{ height: totalHeight }}
        >
          {/* 可见项目容器 */}
          <View 
            className='visible-items-container'
            style={{ 
              transform: `translateY(${offsetY}px)`,
              height: visibleItems.length * itemHeight
            }}
          >
            {visibleItems.map((item, index) => {
              const actualIndex = visibleRange.startIndex + index
              return (
                <View 
                  key={item.id || item._id || actualIndex}
                  className='virtual-item'
                  style={{ height: itemHeight }}
                >
                  {renderItem(item, actualIndex)}
                </View>
              )
            })}
          </View>
        </View>
      </ScrollView>
    </View>
  )
}

export default VirtualList
